package com.cskaoyan.shiro;

import com.cskaoyan.bean.Admin;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.PermissionMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.cskaoyan.utils.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        List<String> strings = adminMapper.selectPasswordByName(username);
        String credential =  strings.size() >= 1?strings.get(0):null;

        return new SimpleAuthenticationInfo(username, credential, this.getName());
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String name = (String) principals.getPrimaryPrincipal();
        List<Admin> admins = adminMapper.selectAdminByName(name);
        Admin admin = admins.size() >= 1?admins.get(0):null;
        if(admin == null){
            return null;
        }

        // 角色
        String roleIds = admin.getRoleIds();
        String[] split = StringUtils.toStringArray(roleIds);

        // 权限
        List<String> permissions = adminMapper.selectPermissionByRoleId(split);
        List<String> roles = roleMapper.selectRoleNameByRoleId(split);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);
        authorizationInfo.addRoles(roles);
        return authorizationInfo;
    }
}
